package pers.wechat.applet;

import com.alibaba.fastjson.JSONObject;
import pers.myutil.network.request.NetworkRequest;
import pers.myutil.network.request.RequestMethod;
import pers.myutil.throwable.network.MyUtilNetworkException;
import pers.wechat.applet.model.LoginInfo;
import pers.wechat.config.WeChatConfig;
import pers.wechat.config.applet.URL;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WeChatAppletLogin {

    public WeChatAppletLogin(WeChatConfig weChatConfig){
        this.weChatConfig = weChatConfig;
    }

    private WeChatConfig weChatConfig;

    /**
     * 获取用户登录信息
     * @param code code
     * @return 用户登录信息
     */
    public LoginInfo getLoginInfo(String code) throws MyUtilNetworkException, IOException {
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("appid",weChatConfig.getAppId());
        map.put("secret",weChatConfig.getAppSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        JSONObject jsonObject = JSONObject.parseObject(NetworkRequest.send(URL.JSCODE2SESSION.getUrl(), RequestMethod.GET,map));
        if(jsonObject.getString("errcode") == null) {
            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setSessionKey(jsonObject.getString("session_key"));
            loginInfo.setOpenId(jsonObject.getString("openid"));
            loginInfo.setUnionId(jsonObject.getString("unionid"));
            return loginInfo;
        }else {
            System.out.println("错误码："+jsonObject.getString("errcode"));
            System.out.println("错误信息："+jsonObject.getString("errmsg"));
        }
        return null;
    }

    public static void main(String[] args) throws MyUtilNetworkException, IOException {
        WeChatConfig weChatConfig = new WeChatConfig.Builder().addAppId("wx05cb2ab1b6670e2d").addAppSecret("581069d9c27965dd6a86850da70abbcf").build();
        System.out.println(new WeChatAppletLogin(weChatConfig).getLoginInfo("021Pv4GW1cFJVZ09msEW1QzaGW1Pv4Gh").toString());
    }
}
